package com.forage.exp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.forage.exp.mapper.UserMapper;
import com.forage.exp.po.User;
import com.forage.exp.po.UserAuthority;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author : George
 * @date : 2022-05-3
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserAccount,userName);
        User user = userMapper.selectOne(queryWrapper);

        //如果没有查询到用户就抛出异常，认证失败
        if(Objects.isNull(user)){
            //所抛出异常在某些情况下会被springSecurity过滤器转换类型导致无法匹配GlobalException
            throw new RuntimeException("用户名或者密码错误");
//            throw new GlobalException(ResponseStatusEnum.AUTHENTICATION_EXCEPTION, "用户名或者密码错误");
        }

        //封装用户信息
        List<String> permissions = new ArrayList<>(Collections.singletonList(user.getUserLevel().getAuthValue()));

        return new UserAuthority(user,permissions);
    }
}
